package net.spacebeeshooter.gui;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashSet;

import javax.swing.JTable;

import net.spacebeeshooter.items.Item;
import net.spacebeeshooter.items.ItemValue;
import net.spacebeeshooter.main.ErrorGenerator;

public class TableSaver {
	
	private Item item;
	private String valueSeparator;
	
	public TableSaver(Item item, String valueSeparator) {
		this.item = item;
		this.valueSeparator = valueSeparator;
	}
	
	public void saveTable(BufferedWriter writer, JTable[] tables) {
		try {
			String newLine = System.getProperty("line.separator");
			ItemValue[] values = item.getValues();
			for (ItemValue value : values) {
				writer.write(value.getName());
				if (value != values[values.length-1]) {
					writer.write(valueSeparator);
				}
			}
			writer.write(newLine);
			for (JTable table : tables) {
				int columnCount = table.getColumnCount();
				HashSet<String> data = new HashSet<String>();
				StringBuilder builder = new StringBuilder();
				for (int x = 0; x != columnCount; x ++) {
					String currentValue = String.valueOf(table.getValueAt(0, x));
					data.add(currentValue);
					builder.append(currentValue);
					if (x != columnCount - 1) {
						builder.append(valueSeparator);
					}
				}
				if (!data.contains("null")) {
					writer.write(builder.toString());
					writer.write(newLine);
				}
				
			}
		} catch (IOException e) {
			new ErrorGenerator().generateErrorMessage("Saving failed.");
		}

	}
}
